<?php

namespace App\Http\Controllers\InternalApi;

use App\Http\Controllers\Controller;
use App\Jobs\Recharge;
use App\Models\NsSupplierGoods;
use App\Models\XnBatchOrder;
use App\Models\XnH5User;
use App\Models\XnMerchant;
use App\Models\XnMyyGoodsInterconnection;
use App\Recharge\Library;
use Carbon\Carbon;
use Illuminate\Http\Request;

class Request_orderController extends Controller
{

    /**
     * @param Request $request
     */
    public function __construct(public Request $request){}
    /**
     *  创建内部活动订单
     */
    public function create_order(Request $request): \Illuminate\Http\JsonResponse
    {
        $params = $request->all();
        $url = 'https://xuniapi.chengmeiyouxuan.com/api/myy_h5/create_order';
        $goods =  XnMyyGoodsInterconnection::query()->where('id',$params['goods_id'])->first();
        $merchant = XnMerchant::query()->where('Merchant_number',$goods->merchant)->first();
        $data = [
            'order_sn'=>$params['order_sn'],
            'account'=>$params['account'],
            'goods_id'=>$params['goods_id'],
        ];
        ksort($data);
        $params['sign'] = md5(json_encode($data).$merchant->secret_key);
        $curl = httpClient()->asJson()->post($url, $params);
        if (!$curl['success']){
            return fails('创建订单失败');
        }
        $data = [
            'order'=>$params['order_sn'].'H5',
            'account'=>$params['account'],
            'time'=>date('Y-m-d H:i:s',time())
        ];
        return successly($data);
    }

    public function order($orderInfo){
        $time = Carbon::now();
        $good = XnMyyGoodsInterconnection::query() -> where('id',$orderInfo['gid']) -> first();
        $order = [
            'gid'                   => 1,
            'goodsId'               => $good->id,
            'userName'              => $orderInfo['account'],
            'productType'           => 0,
            'orderNum'              => $orderInfo['order_no'],
            'price'                 => $good->price,
            'unitPrice'             => $good->unit_price,
            'rechargeNum'           => $orderInfo['num'],
            'rechargeMoney'         => $orderInfo['money'],
            'recharge_time'         => $time,
            'recharge_status'       => 0,
            'place_order_people'    => 'H5联合商品下单',
            'goodsName'             => $good->g_name,
            'ip'                    => $this->request->ip(),
            'merchantOrderNum'      => $orderInfo['alipay_order'],
            'business'              => 19,  //h5联合商品下单
            'Merchant_number'       => $good->merchant,
            'myy_h5_type'           => 1,
        ];
        // 账单
        $order_bill = [
            'supplier_id'       => 1,
            'goods_explain'     => $good->g_name . '商品',
            'bookkeeping_type'  => 1,
            'order_num'         => $order['orderNum'],
            'account'           => $order['userName'],
            'price'             => $good->price,
            'goods_num'         => $order['rechargeNum'],
            'business_type'     => $order['business'],
            'budget_money'      => $order['rechargeMoney'],
            'ctime'             => date('Y-m-d H:i:s'),
            'goods_id'          => $good->id,
            'brand_id'          => $good->brand_id,
            'merchant_name'     => $order['place_order_people'],
            'refund_time'       => '1970-01-01 08:00:00'
        ];
        $Merchant_info = XnMerchant::query()->where('Merchant_number',$good->merchant)->first();
        $merchant_bill = [
            'merchant_number'=>$good->merchant,
            'time'=>date('Y-m-d H:i:s',time()),
            'status'=>2,
            'before_transaction_balance'=>$Merchant_info['balance'],
            'transaction_amount'=>$order['rechargeMoney'],
            'after_transaction_balance'=>($Merchant_info['balance']-$order['rechargeMoney']),
            'merchant_order'=>$order['orderNum'],
            'trading_status'=>5,
        ];
        Recharge::dispatch( $order, $merchant_bill, $order_bill, $good, '')->onQueue('h5_order_job');
    }

    public function H5_goods_list(){
        $res = XnMyyGoodsInterconnection::query()->paginate(10);
        if (!$res){
            return fails('查询失败');
        }
        return successly($res,'200','查询成功');
    }

    public function H5_order_48_error(Request $request){
        $params = $request->all();

        $order = XnBatchOrder::query()->where('merchantOrderNum',$params['order_sn'])->first();
        if (!$order){
            return fails('订单不存在');
        }
        // 添加时间有效性验证（需先于退款状态检查）
        if (Carbon::parse($order->recharge_time)->lt(now()->subHours(48))) {
            return fails('订单已过期');
        }
        return successly();
    }

    //h5页面判断登陆手机号是否为年卡或者季卡

    public function h5_is_phone_card(Request $request){
        $params = $request->all();
        $h5_goods = XnMyyGoodsInterconnection::query()
            ->where('status',1)
            ->get();
        $goods = NsSupplierGoods::query()
            ->wherein('id', $h5_goods->pluck('g_id'))
            ->get();
        if (!$goods){
            return fails('未检测到活动商品');
        }
        $order = XnBatchOrder::query()
            ->where('userName',$params['phone'])
            ->wherein('brand_id',$goods->pluck('brand_id'))
            ->where('recharge_status',3)
            ->where('tob_refund',2)
            ->where('business',7)
//            ->whereNotIn('goodsId', $goods->pluck('id'))
            ->select('merchantOrderNum','userName','goodsName','goodsId','brand_id')
            ->get();
        $order = json_decode(json_encode($order),true);
        if (empty($order)){
            return fails('未找到该账号可充值的活动订单');
        }
        foreach ($order as $k=>$v){
            $order[$k]['h5_myy_gid'] = XnMyyGoodsInterconnection::query()->where('brand_id',$v['brand_id'])->value('id');
            $orders = XnBatchOrder::query()
                ->where('merchantOrderNum',$v['merchantOrderNum'].'H5')
                ->select('merchantOrderNum','userName','goodsName')
                ->first();
            if ($orders){
                unset($order[$k]);
            }

        }
        return successly($order);
    }
}
